package logic

import (
	"context"
	"errors"
	"gorm.io/gorm"
	"users/models"
	"users/pkg"

	"users/userrpc/internal/svc"
	"users/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *userrpc.RegisterRequest) (*userrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	var user models.User
	mobile, err := user.FindUserByMobile(in.Mobile)
	if err != nil {
		return nil, err
	}
	if mobile.ID != 0 {
		return nil, errors.New("当前用户已存在")
	}
	user = models.User{
		Model:    gorm.Model{},
		Mobile:   in.Mobile,
		Password: pkg.Md5Str(in.Password),
	}
	add, err := user.UserAdd()
	if err != nil {
		return nil, errors.New("用户注册失败")
	}
	return &userrpc.RegisterResponse{
		UserId: int64(add.ID),
	}, nil
}
